import { axiosMock, delayFn, randArrItem } from '@/services/axiosMock'
import { DEFAULT_PAGE_SIZE } from '@/utils/pagination'
import { IEventTemplateODTO, IEventTemplateRes, IEventTemplateTabCountRes } from '../interface'

const MOCK_TOTAL = 2500

// 随机选取若干不重复元素
const pickSome = <T>(arr: T[], min = 1, max = arr.length) => {
  const len = Math.max(min, Math.min(max, Math.floor(Math.random() * max) + 1))
  const pool = [...arr]
  const out: T[] = []
  for (let i = 0; i < len && pool.length; i++) {
    const idx = Math.floor(Math.random() * pool.length)
    out.push(pool[idx])
    pool.splice(idx, 1)
  }
  return out
}

const createItem = (idx: number): IEventTemplateODTO => {
  const id = idx + 1
  const now = Date.now()
  const fmt = (ts: number) => new Date(ts).toISOString()
  const oneToFive = [1, 2, 3, 4, 5]
  const createdTs = now - 24 * 60 * 60 * 1000 * randArrItem(oneToFive)
  const updatedTs = Math.max(createdTs + 60 * 1000, now - 10 * 60 * 1000 * randArrItem(oneToFive))
  return {
    eventTemplateId: id,
    templateCn: `中文模板描述 ${id}`,
    templateEn: `English template ${id}`,
    // 2位大写字母数字，符合表单校验
    statusCode: randArrItem(['CR', 'IN', 'EX', 'DW']),
    reasonCode: randArrItem(['EA', 'RC', 'OT']),
    shipTrackRequire: randArrItem([1, 2]),
    messageType: randArrItem([1, 2, 3]),
    statusGroup: randArrItem([1, 2, 3, 4, 5]),
    status: randArrItem([11, 12, 13, 21, 22, 23, 24, 31, 32, 33, 41, 42, 43, 51, 52, 53]),
    firstLines: pickSome([1, 2, 3, 4]),
    tailLines: pickSome([1, 2, 3]),
    locationType: randArrItem([1, 2, 3, 4, 5, 6]),
    visibleFlag: randArrItem([0, 1]),
    enableFlag: randArrItem([0, 1]),
    timestampDescription: randArrItem(['节点时间', '系统时间']),
    updateAt: fmt(updatedTs),
  }
}

const ITEM_CACHE = new Map<number, IEventTemplateODTO>()
const getItemById = (id: number) => {
  if (!ITEM_CACHE.has(id)) ITEM_CACHE.set(id, createItem(id - 1))
  return ITEM_CACHE.get(id) as IEventTemplateODTO
}

export const LIST_DATA_MOCK: IEventTemplateRes = {
  total: MOCK_TOTAL,
  size: DEFAULT_PAGE_SIZE,
  current: 1,
  pages: Math.ceil(MOCK_TOTAL / DEFAULT_PAGE_SIZE),
  records: Array(DEFAULT_PAGE_SIZE)
    .fill(null)
    .map((_item, idx) => getItemById(idx + 1)),
}

axiosMock('default', mock => {
  // 轨迹事件模板列表
  mock.onPost(`/tmsapi/event_template/list`).reply(
    delayFn<IEventTemplateRes>(600, ({ data }) => {
      const size = +data?.size || DEFAULT_PAGE_SIZE
      const page = +data?.page || 1
      const pages = Math.ceil(MOCK_TOTAL / size)

      return {
        success: true,
        data: {
          total: MOCK_TOTAL,
          size,
          current: page,
          pages,
          records: Array(size)
            .fill(null)
            .map((_item, idx) => getItemById((page - 1) * size + idx + 1)),
        },
      }
    }),
  )

  // 轨迹事件模板新增
  mock.onPost(`/tmsapi/event_template/add`).reply(
    delayFn(600, () => {
      return { success: true }
    }),
  )

  // 轨迹事件模板详情
  mock.onPost(`/tmsapi/event_template/get`).reply(
    delayFn(600, ({ data }) => {
      const eventTemplateId = +(data?.eventTemplateId ?? data?.event_template_id) || 0
      const item = eventTemplateId > 0 ? getItemById(eventTemplateId) : {}
      return { success: true, data: item }
    }),
  )

  // 轨迹事件模板更新
  mock.onPost(`/tmsapi/event_template/update`).reply(
    delayFn(600, () => {
      return { success: true }
    }),
  )

  // 轨迹事件模板标签数量
  mock.onPost(`/tmsapi/event_template/tab/count`).reply(
    delayFn<IEventTemplateTabCountRes[]>(600, () => {
      return {
        success: true,
        data: [
          { count: 99, tabId: 0 },
          { count: 88, tabId: 1 },
          { count: 11, tabId: 2 },
        ],
      }
    }),
  )
})
